package com.zhiban.project.util;

import java.io.StringWriter;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {

	public static String writeObject(Object obj) {
		ObjectMapper mapper = new ObjectMapper();
		StringWriter writer = new StringWriter();
		String re = null;
		try {
			JsonGenerator json = new JsonFactory().createGenerator(writer);
			mapper.writeValue(json, obj);
			re = writer.toString();
			json.close();
			writer.close();
		} catch (Exception e) {
			throw new RuntimeException("json转换异常", e);
		}
		return re;
	}

	/**
	 * @param <T>
	 *            泛型声明
	 * @param json
	 *            JSON字符串
	 * @param clzz
	 *            要转换对象的类型
	 * @return
	 */
	public static <T> T fromJson(String json, Class<T> clzz) {
		ObjectMapper mapper = new ObjectMapper();
		T t = null;
		try {
			t = mapper.readValue(json, clzz);
		} catch (Exception e) {
			throw new RuntimeException("json转换异常", e);
		}
		return t;
	}
}
